import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, history, FormattedMessage } from 'umi';
// import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import AppWizardModal from './components/AppWizardModal';
import { listAppsInfo, addApp, removeApp, listHostsInfo } from '@/services/configserver/api';
import styles from './index.less';
import { JSONObject } from 'puppeteer-core';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAddApp = async (fields: API.AppsInfoListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addApp({ ...fields });
        hide();
        message.success('添加成功');
        console.log('HostsInfoList Event=handleAddApp,value=', fields)
        return true;
    } catch (error) {
        hide();
        message.error('添加失败');
        return false;
    }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param fileds
 */
const handleRemoveApp = async (fileds: API.AppsInfoListItem) => {
    const hide = message.loading('正在删除');
    console.log('AppsInfoList Event=handleRemoveApp,value=', fileds);

    try {
        await removeApp({
            id: fileds.id,
            hostname: fileds.hostname,
        });
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败');
        return false;
    };
}


// React.FC<>的在typescript使用的一个泛型，
// FC就是FunctionComponent的缩写，是函数组件，
// 我们使用React.FC来写 React 组件的时候，是不能用setState的，取而代之的是useState()、useEffect等 Hook API。
const AppsInfoList: React.FC = () => {
    /**
 * @en-US International configuration
 * @zh-CN 国际化配置
 * */
    const intl = useIntl();

    const setHostListValue = async () => {

        let data = JSON.parse('{"current":1,"pageSize":20,"sort":{}}');

        try {
            // 1. 返回了host list
            // 2. 组装成 map

            //要传入必要分页参数
            const hostList = await listHostsInfo(data);
            console.log('AppInfoList Event=setHostListValue,value=', hostList.data);

            //valueEnum 接受map对象 
            let listInfoOption = new Map();
            hostList.data?.forEach((val) => {
                listInfoOption.set(val.hostname, val.hostname);
            })
            sethostList(listInfoOption);

            return true;
        } catch (error) {
            message.error('获取host列表失败');
            return false;
        }
    }


    useEffect(() => {
        setHostListValue();
    }, []);

    /**
    * @en-US Pop-up window of add app wizard
    * @zh-CN 新建添加或者update，更具values值来判断应用的向导弹窗
    *  */
    const [appWizardModalVisible, handleAppWizardModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<API.AppsInfoListItem>();
    const [hostlist, sethostList] = useState<Map<string, JSONObject>>();


    const columns: ProColumns<API.AppsInfoListItem>[] = [
        {
            title: (
                <FormattedMessage
                    id="pages.listAppsInfoTable.id"
                    defaultMessage="ID"
                />
            ),
            dataIndex: 'id',
            tip: '数据库ID',
            search: false,
            hideInTable: true,

        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.app_name" defaultMessage="Appname" />,
            dataIndex: 'app_name',
            sorter: true,
            valueType: 'textarea',
            fixed: 'left',
            width: 240,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.apptype" defaultMessage="AppType" />,
            dataIndex: 'apptype',
            valueType: 'textarea',
            width: 240,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.solution" defaultMessage="Solution" />,
            dataIndex: 'solution',
            valueType: 'textarea',
            search: false,
            width: 180,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.version" defaultMessage="Version" />,
            dataIndex: 'version',
            valueType: 'textarea',
            search: false,
            width: 120,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.hostname" defaultMessage="Hostname" />,
            dataIndex: 'hostname',
            valueType: 'textarea',
            width: 180,
            valueEnum: hostlist,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.ip" defaultMessage="IP" />,
            dataIndex: 'ip',
            valueType: 'textarea',
            search: false,
            width: 140,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.port" defaultMessage="PORT" />,
            dataIndex: 'port',
            valueType: 'textarea',
            search: false,
            width: 80,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.command" defaultMessage="Command" />,
            dataIndex: 'command',
            valueType: 'textarea',
            search: false,
            width: 240,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.titleStatus" defaultMessage="Status" />,
            dataIndex: 'solution',
            hideInForm: true,
            hideInTable: true,
            width: 120,
            valueEnum: {
                "freelink": {
                    text: (
                        <FormattedMessage
                            id="pages.listAppsInfoTable.nameStatus.default"
                            defaultMessage="Shut down"
                        />
                    ),
                    status: 'Default',
                },
                "valuelink": {
                    text: (
                        <FormattedMessage id="pages.listAppsInfoTable.nameStatus.processing" defaultMessage="Processing" />
                    ),
                    status: 'Processing',
                },
                "smartlink": {
                    text: (
                        <FormattedMessage id="pages.listAppsInfoTable.nameStatus.online" defaultMessage="Online" />
                    ),
                    status: 'Success',
                },
                default: {
                    text: (
                        <FormattedMessage
                            id="pages.listAppsInfoTable.nameStatus.abnormal"
                            defaultMessage="Abnormal"
                        />
                    ),
                    status: 'Error',
                },
            },
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.image" defaultMessage="Image" />,
            dataIndex: 'image',
            valueType: 'textarea',
            search: false,
            hideInTable: true
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.workdir" defaultMessage="Workdir" />,
            dataIndex: 'workdir',
            valueType: 'textarea',
            search: false,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.logdir" defaultMessage="Logdir" />,
            dataIndex: 'logdir',
            valueType: 'textarea',
            search: false,
        },
        {
            title: <FormattedMessage id="pages.listAppsInfoTable.titleOption" defaultMessage="Operating" />,
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            width: 160,
            render: (_, record) => [
                <a
                    key="details"
                    onClick={async () => {
                        console.log("AppsInfoList 表单: Event=details.onClick,value=", record);
                        setCurrentRow(record);
                        let detailPath = '/configinfo/appcfg?id=' + record.id + '&appname=' + record.app_name;
                        history.push(detailPath);
                    }}
                >
                    <FormattedMessage id="pages.listAppsInfoTable.details" defaultMessage="Details" />
                </a>,
                <a
                    key="update"
                    onClick={() => {
                        console.log("AppsInfoList 表单: Event=update.onClick,value=", record);
                        handleAppWizardModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    <FormattedMessage id="pages.listAppsInfoTable.update" defaultMessage="Update" />
                </a>,
                <a
                    key="remove"
                    onClick={async () => {
                        console.log("AppsInfoList 表单: Event=remove.onClick,value=", record);
                        setCurrentRow(record);
                        const success = await handleRemoveApp(record);
                        if (success) {
                            setCurrentRow(undefined);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    className={styles.listhostOperationRemove}
                >
                    <FormattedMessage id="pages.listAppsInfoTable.remove" defaultMessage="Remove" />
                </a>,
            ],
        },
    ];

    return (
        // <PageContainer>
        <>
            <ProTable<API.AppsInfoListItem, API.PageParams>
                headerTitle={intl.formatMessage({
                    id: 'pages.listAppsInfoTable.title',
                    defaultMessage: 'Enquiry form',
                })}
                actionRef={actionRef}
                // rowKey表示每一行的key
                rowKey="id"
                search={{
                    // labelWidth: 60,
                    span: 6,
                }}
                scroll={{ x: 2600 }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleAppWizardModalVisible(true);
                            console.log("AddAppWizardForm 表单: Event=handleAppWizardModalVisible(true)");
                            console.log(currentRow)
                        }}
                    >
                        <PlusOutlined /> <FormattedMessage id="pages.listAppsInfoTable.new" defaultMessage="New" />
                    </Button>,
                ]}
                request={listAppsInfo}
                columns={columns}
            />
            {/* 添加APP wizard form*/}
            <AppWizardModal
                onFinish={async (value) => {
                    console.log("AddAppWizardForm 表单: Event=onFinish,value =", value);
                    const success = await handleAddApp(value);
                    if (success) {
                        handleAppWizardModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                    // 重置一下step form 表单的
                    // StepForm 与 ProForm 完全相同，只是 onFinish 支持了 Promise，如果返回 false, 就不会跳转下一步。 
                    // | onFinish | 表单提交成功触发 | (values:T)=>Promise<false> | - |
                    setCurrentRow(undefined);
                    return true
                }}

                onCancel={() => {
                    console.log("AddAppWizardForm 表单: Event=onClose");
                    handleAppWizardModalVisible(false);
                    setCurrentRow(undefined);
                }}
                onVisibleChange={(visible) => {
                    if (visible) {
                        console.log("AddAppWizardForm 表单: Event=onVisibleChange -> 显示AddHostForm");
                    } else {
                        console.log("AddAppWizardForm 表单: Event=onVisibleChange -> 关闭AddHostForm");
                    }
                    handleAppWizardModalVisible(visible);
                }}

                appWizardModalVisible={appWizardModalVisible}

                values={currentRow || {}}
            />
        </>
        //  </PageContainer> 
    );
};

export default AppsInfoList;
